<template>
<div>
  <q-modal ref="avatarEditModal" :content-css="{minWidth: '80vw', minHeight: '80vh'}">
    <q-modal-layout>
      <q-toolbar slot="header">
        <q-btn color="warning" big  flat @click="closeAvatarModal">取消 </q-btn>
        <q-toolbar-title class="text-center">
            编辑头像
        </q-toolbar-title>
      </q-toolbar>

      <div>
        <div class="model">
          <div>
            <div class="content-layout">
              <!--
                参考：https://github.com/xyxiao001/vue-cropper/blob/f3ca6c170c0e3a406ce00fec0de61b98796402d3/README.md
                img	裁剪图片的地址	空	url 地址 || base64 || blob
                outputSize	裁剪生成图片的质量	1	0.1 - 1
                outputType	裁剪生成图片的格式	jpg (jpg 需要传入jpeg)	jpeg || png || webp
                info	裁剪框的大小信息	true	true || false
                canScale	图片是否允许滚轮缩放	true	true || false
                autoCrop	是否默认生成截图框	false	true || false
                autoCropWidth	默认生成截图框宽度	容器的80%	0~max
                autoCropHeight	默认生成截图框高度	容器的80%	0~max
                fixed	是否开启截图框宽高固定比例	true	true | false
                fixedNumber	截图框的宽高比例	[1 : 1]	[宽度 : 高度]
                full	是否输出原图比例的截图	false	true | false
                fixedBox	固定截图框大小 不允许改变	false	true | false
                canMove	上传图片是否可以移动	true	true | false
                canMoveBox	截图框能否拖动	true	true | false
                original	上传图片按照原始比例渲染	false	true | false
              -->
              <vueCropper
                ref="cropper"
                :img="imagesrc"
                :outputSize="0.6"
                :original="false"
                :fixed="true"
                :autoCrop="true"
                :autoCropWidth="250"
                :autoCropHeight="250"
              ></vueCropper>
            </div>
            <div>
              <label for="uploads" class="btn outline">重选</label>
              <label @click="getFile" class="btn">确定</label>
            </div>
          </div>
        </div>
      </div>

    </q-modal-layout>
  </q-modal>
  <label for="uploads">
        <slot name="selectfile"></slot>
  </label>
  <input type="file" id="uploads" style="display:none" accept="image/*"
    @change="selectImage($event, 1)">
</div>
</template>

<script>
import {
  QBtn,
  QModal,
  QModalLayout,
  QToolbar,
  QToolbarTitle,
  QIcon,
  Alert,
  Dialog
} from "quasar";
import vueCropper from "./vue-cropper";
export default {
  components: {
    QBtn,
    QModal,
    QModalLayout,
    QToolbar,
    QToolbarTitle,
    QIcon,
    vueCropper,
    Alert,
    Dialog
  },
  data: function() {
    return {
      imagesrc: ""
    };
  },
  mounted() {
    // this.openAvatarModal();
  },
  methods: {
    closeAvatarModal(){
       this.$refs.avatarEditModal.close();
       console.log('清除文件');
       document.getElementById('uploads').value='';
       this.imagesrc=""
    },
    openAvatarModal() {
      this.$refs.avatarEditModal.open();
    },
    getFile() {
      this.$refs.cropper.getCropBlob(data => {
        console.log("编辑的头像文件：", data);
        this.$emit("get-file", data);
         this.$refs.avatarEditModal.close();
      });
    },
    showSelectLoading(_delay) {
      if(!_delay) {_delay = 2000}
      const _temp = Dialog.create({
        message: "正在处理中，请稍后...",
        progress: {
          indeterminate: true
        },
        buttons: [
          {
            label: "知道了",
            handler(data) {
              clearTimeout(timeout);
            }
          }
        ]
      });
      const timeout = setTimeout(() => {
        clearTimeout(timeout);
        _temp.close();
      }, _delay);
    },
    alertMsg(msg) {
      if (msg) {
        const _errAlert = Alert.create({
          color: 'warning',
          icon: 'info',
          html: msg,
          position: 'bottom',
        });
         setTimeout(()=>{
          _errAlert.dismiss();
        },3000);
      }
    },
    checkFile(file, isDistinct) {//校验文件
      //类型
      if (
        !file ||
        !file.name ||
        !/.*(.jpg|.png|.gif|.jpeg|bmp)$/.test(file.name)
      ) {
        this.alertMsg("抱歉，不支持的文件类型");
        return false;
      }
      const _size = !isDistinct ? 5242880 : 1048576;
      //大小
      if (file.size > _size) {
        //5M
        this.alertMsg("抱歉，文件大小超出了5M的限制");
        return false;
      }
      return true;
    },
    selectImage(e, num) {
      // this.option.img
      const file = e.target.files[0];
      console.log('选择的文件：',file);
      if(!file) {
        return false;
      }
      if (!this.checkFile(file)) {
        return false;
      }
      if (typeof FileReader === "undefined") {
        this.alertMsg("抱歉，您的设备不支持图片处理");
        //不支持类型的处理
        return false;
      }
      this.openAvatarModal();
      this.showSelectLoading()
      const reader = new FileReader();
      reader.onload = e => {
        let data = e.target.result;
        this.imagesrc = data;
      };
      //  if (typeof e.target.result === "object") {
      //     // 把Array Buffer转化为blob 如果是base64不需要
      //     data = window.URL.createObjectURL(new Blob([e.target.result]));
      //   } else {
      //     data = e.target.result;
      //   }
      // 转化为base64,reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsDataURL(file)
      // reader.readAsArrayBuffer(file);
    }
  }
};
</script>
<style>
* {
  margin: 0;
  padding: 0;
}
.btn {
  display: inline-block;
  line-height: 1;
  cursor: pointer;
  border: 1px solid #c0ccda;
  padding: 9px 15px;
  color: #f2c037;
  background-color: #607d8b;
  border-color: #ebeb17;
  transition: all 0.2s ease;
  width: 49%;
  text-align:center;
}
.outline {
  color: black;
  background-color: white
}
.btn:active {
  background-color: #606457;
}
.content-layout {
  height: 360px;
  width: 280px;
}
.model {
  position: fixed;
  z-index: 10;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow: auto;
  top: 0;
  left: 0;
  /* background: rgba(0, 0, 0, 0.8); */
}
@keyframes slide {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: -100% 0;
  }
}
</style>